package com.vdg.fps.ulti;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.message.BasicNameValuePair;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import com.vdg.fps.config.ErrorCode;
import com.vdg.fps.config.FPSConfig;
import com.vdg.fps.data.FaceBookAccount;
import com.vdg.fps.listener.OnHttpResponse;
import com.vdg.fps.services.FPSService;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap.Config;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.widget.Toast;

public class Utilities {
	private static String TAG = "Utilities";
	private final static String PRE_NAME = "cfgprefrence";

	public static String getDataDir(Context context) {
		try {
			return context.getPackageManager().getPackageInfo(
					context.getPackageName(), 0).applicationInfo.dataDir;
		} catch (Exception e) {
			Log.w("Your Tag", "Data Directory error:", e);
			return null;
		}
	}

	public static String substring(String source, String pattern, char endStr) {
		int idxS = source.indexOf(pattern);
		if (idxS >= 0) {
			int idxE = source.indexOf(endStr, idxS + pattern.length());
			if (idxE > idxS) {
				return source.substring(idxS + pattern.length(), idxE);
			}
		}
		return "";
	}

	public static void showToast(String message, Context context) {
		Toast.makeText(context, message, Toast.LENGTH_LONG).show();
	}

	public static void showLongToast(String message, Context context) {
		final Toast toast = Toast
				.makeText(context, message, Toast.LENGTH_SHORT);
		toast.show();
		Handler handler = new Handler();
		handler.postDelayed(new Runnable() {
			@Override
			public void run() {
				toast.cancel();
			}
		}, 5000);
	}

	public static void showError(int errorCode, Context context) {
		if (errorCode == ErrorCode.REQUEST_TIME_OUT_ERROR) {
			Toast.makeText(context, "Request time out, please try again!",
					Toast.LENGTH_LONG).show();
			return;
		}
		Toast.makeText(context, "error code = " + String.valueOf(errorCode),
				Toast.LENGTH_LONG).show();
	}

	public static void startSaveFile(final String dirName,
			final String fileName, final Context context, final byte[] byteArr) {
		final Handler handler = new Handler();
		(new Thread() {
			public void run() {
				try {
					saveFile(dirName, fileName, context, byteArr);
					handler.post(new Runnable() {

						@Override
						public void run() {
							// TODO Auto-generated method stub
							showLongToast("Save file " + fileName + " to: "
									+ FPSConfig.DATA_FOLDER + "/" + dirName
									+ "  sucessfully", context);
						}
					});
				} catch (final IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					handler.post(new Runnable() {

						@Override
						public void run() {
							// TODO Auto-generated method stub
							showToast(
									"Save file " + fileName + " Error :"
											+ e.getMessage(), context);
						}
					});
				}
			};
		}).start();
	}

	public static void saveFile(String dirName, String fileName,
			Context context, byte[] byteArr) throws IOException {
		File sdcard = Environment.getExternalStorageDirectory();
		File root = new File(sdcard, "FPS");
		if (!root.exists()) {
			root.mkdir();
		}
		File mydir = new File(root, dirName);
		if (!mydir.exists()) {
			mydir.mkdir();
		}
		File fileWithinMyDir = new File(mydir, fileName);
		Log.v(TAG, "file path= " + fileWithinMyDir.getAbsolutePath());
		FileOutputStream out = new FileOutputStream(fileWithinMyDir);
		out.write(byteArr);
		out.flush();
		out.close();

	}

	public static boolean sdcardIsMounting() {
		if (!Environment.MEDIA_MOUNTED.equals(Environment
				.getExternalStorageState())) {
			return true;
		} else {
			return false;
		}
	}

	// read more about Environment class :
	// http://developer.android.com/reference/android/os/Environment.html
	public static String getDownloadFolder(Context context) {
		return context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)
				.toString();
	}

	public static boolean isValidEmail(String email) {
		boolean isValidEmail = false;

		String emailExpression = "^[\\w\\.-]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";
		CharSequence inputStr = email;

		Pattern pattern = Pattern.compile(emailExpression,
				Pattern.CASE_INSENSITIVE);
		Matcher matcher = pattern.matcher(inputStr);
		if (matcher.matches()) {
			isValidEmail = true;
		}
		return isValidEmail;
	}

	public static boolean isMyServiceRunning(Activity activity) {
		ActivityManager manager = (ActivityManager) activity
				.getSystemService(Context.ACTIVITY_SERVICE);
		for (RunningServiceInfo service : manager
				.getRunningServices(Integer.MAX_VALUE)) {
			if (FPSService.class.getName().equals(
					service.service.getClassName())) {
				return true;
			}
		}
		return false;
	}

	public static boolean networkConnected(Context wrapper) {
		Context ctx = wrapper.getApplicationContext();
		ConnectivityManager connMgr = (ConnectivityManager) ctx
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo info = connMgr.getActiveNetworkInfo();
		return info != null && info.isConnected();
	}

	public static String getTimeDisplay(Long time) {
		return new SimpleDateFormat("dd/MM/yyyy hh:mm:ss")
				.format(new Date(time));
	}

	public static String getStringFromSharedPreferences(String key,
			Context context) {
		SharedPreferences mPrefrence = context
				.getSharedPreferences(PRE_NAME, 0);
		if (mPrefrence == null) {
			return "";
		}
		return mPrefrence.getString(key, "");
	}

	public static boolean saveStringToSharedPreferences(String save,
			Context context, String key) {
		SharedPreferences mPrefrence = context
				.getSharedPreferences(PRE_NAME, 0);
		Editor mPrefrenceEdit = mPrefrence.edit();
		if (mPrefrenceEdit == null) {
			return false;
		}
		mPrefrenceEdit.putString(key, save);
		return mPrefrenceEdit.commit();
	}

	public static String readFile(File file) {
		StringBuilder text = new StringBuilder();
		try {
			BufferedReader br = new BufferedReader(new FileReader(file));
			String line;

			while ((line = br.readLine()) != null) {
				text.append(line);
				text.append('\n');
			}
			br.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return text.toString();
	}
	// doc.LoadHtml(sourceCode);
	// var nDTSG1 =
	// doc.DocumentNode.SelectNodes("//input[@name=\"fb_dtsg\"]");
	// if (nDTSG1 != null && nDTSG1.Count > 0) {
	// var ndtsg = nDTSG1.FirstOrDefault();
	// return ndtsg.GetAttributeValue("value", "");
	// }
	// return "";
	// }
}